<template>
  <div id="homePage">
    <!-- 搜索框 -->
    <div class="search-bar">
      <a-input-search
        placeholder="从海量笔记中搜索"
        v-model:value="searchParams.searchText"
        enter-button="搜索"
        size="large"
        @search="doSearch"
      />
    </div>

    <!-- 分类 + 标签 -->
     <div class="category-bar">
       <a-flex justify="space-between" align="center">
         <a-tabs v-model:activeKey="selectedCategory" @change="doSearch">
           <a-tab-pane key="all" tab="全部" />
           <a-tab-pane v-for="category in categoryList" :key="category" :tab="category.categoryName" />
         </a-tabs>
         <a-button 
           v-if="isAdmin" 
           type="primary" 
           @click="clearNotesCache"
           style="margin-right: 20px"
         >
           清除笔记缓存
         </a-button>
       </a-flex>
     </div>
    <div class="tag-bar">
      <span style="margin-right: 8px">标签：</span>
      <a-space :size="[0, 8]" wrap>
        <a-checkable-tag
          v-for="(tag, index) in tagList"
          :key="tag"
          v-model:checked="selectedTagList[index]"
          @change="doSearch"
        >
          {{ tag.tagName }}
        </a-checkable-tag>
      </a-space>
    </div>

    <!-- 笔记列表 -->
    <a-list
      :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }"
      :data-source="dataList"
      :pagination="pagination"
      :loading="loading"
      style="margin-left: 20px"
    >
      <template #renderItem="{ item: note }">
        <a-list-item style="padding: 0">
          <!-- 单张图片 -->
          <a-card hoverable @click="doClickNotes(note)">
            <template #cover>
              <img
                style="height: 180px; object-fit: cover"
                :alt="note.title"
                :src="note.cover || '/note.jpg'"
              />
            </template>
            <div class="note-content">
              <div class="note-title">{{ note.title }}</div>
              <div class="note-meta">
                <div class="user-info">
                  <a-avatar :src="note.user.userAvatar || '/avatar.png'" />
                  <span class="username">{{ note.user.userName || '匿名用户' }}</span>
                </div>
                <div class="tags-container">
                  <a-tag color="green">
                    {{ getCategoryName(note.categoryId) }}
                  </a-tag>
                  <a-tag v-for="tag in note.tagList" :key="tag.id">
                    {{ tag.tagName }}
                  </a-tag>
                </div>
              </div>
            </div>
          </a-card>
        </a-list-item>
      </template>
    </a-list>
  </div>
</template>

<script setup lang="ts">
// 数据
import { computed, onMounted, reactive, ref } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { listNotesVoByPageUsingPost, listNoteTagsCategoryUsingGet, clearAllNotesCacheUsingGet } from '@/api/notesController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode } from 'vue'

const dataList = ref<API.NotesVO[]>([])
const total = ref(0)
const loading = ref(true)

// 搜索条件
const searchParams = reactive<API.NotesQueryRequest>({
  current: 1,
  pageSize: 12,
  sortField: 'create_time',
  sortOrder: 'descend',
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    // 切换页号时，会修改搜索参数并获取数据
    onChange: (page: number, pageSize: number) => {
      searchParams.current = page
      searchParams.pageSize = pageSize
      fetchData()
    },
  }
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  // 转换搜索参数
  const params = {
    ...searchParams,
    tags: [] as API.Tags[],
  }
  if (selectedCategory.value !== null) {
    params.categoryId = selectedCategory.value.id
  }
  selectedTagList.value.forEach((useTag, index) => {
    if (useTag) {
      params.tags.push(tagList.value[index])
    }
  })
  const res = await listNotesVoByPageUsingPost(params)
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  loading.value = false
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

const doSearch = () => {
  // 重置搜索条件
  searchParams.current = 1
  fetchData()
}

const categoryList = ref<API.Categories[]>([])
const selectedCategory = ref('all')
const tagList = ref<API.Tags[]>([])
const selectedTagList = ref<API.Tags[]>([])

// 获取系统预设标签和分类选项
const getTagCategoryOptions = async () => {
  const res = await listNoteTagsCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // 转换成下拉选项组件接受的格式
    categoryList.value = res.data.data.categoriesList ?? []
    tagList.value = res.data.data.tagsList ?? []
  } else {
    message.error('加载分类标签失败，' + res.data.message)
  }
}

onMounted(() => {
  getTagCategoryOptions()
})
const router = useRouter()
// 跳转至图片详情
const doClickNotes = (Note: API.NotesVO) => {
  router.push({
    path: `/note/${Note.id}`,
  })
}

const getCategoryName = (categoryId: number) => {
  const category = categoryList.value.find(cat => cat.id === categoryId)
  return category ? category.categoryName : '默认'
}

const loginUserStore = useLoginUserStore()
const isAdmin = computed(() => loginUserStore.loginUser?.userRole === 'admin')

// 清除笔记缓存
const clearNotesCache = () => {
  Modal.confirm({
    title: '确认清除缓存',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确定要清除所有笔记缓存吗？清除后将重新从数据库加载数据。',
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      try {
        const res = await clearAllNotesCacheUsingGet()
        if (res.data.code === 0) {
          message.success('清除缓存成功')
          // 重新加载数据
          fetchData()
        } else {
          message.error('清除缓存失败：' + res.data.message)
        }
      } catch (error: any) {
        message.error('清除缓存失败：' + error.message)
      }
    },
  })
}
</script>

<style scoped>
#homePage {
  margin-bottom: 16px;

  .search-bar {
    max-width: 480px;
    margin: 0 auto 16px;
  }

  .category-bar {
    margin-left: 20px;
  }

  .tag-bar {
    margin-bottom: 20px;
    margin-left: 20px;
  }

  .note-content {
    .note-title {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 12px;
      text-align: center;
      color: rgba(0, 0, 0, 0.85);
    }

    .note-meta {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;

      .username {
        color: rgba(0, 0, 0, 0.65);
      }
    }

    .tags-container {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
    }
  }
}
</style>
